package gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;

import java.awt.Stroke;
import javax.swing.JPanel;

import klotski.KlotskiBoard;
import klotski.ProtoBlock;

public class BoardPanel extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    final static int edge = 80;
    KlotskiBoard board;

    BoardPanel() {
//        this.board = board;
//        setPreferredSize(new Dimension(edge * board.w, edge * board.h));
    }

    public void setBoard(KlotskiBoard board) {
        this.board = board;
        setPreferredSize(new Dimension(edge * board.w, edge * board.h));      
    }

    class MyPoly extends Polygon {

        /**
         *
         */
        private static final long serialVersionUID = 1L;

        void setArray(int[][] a) {
            xpoints = a[0];
            ypoints = a[1];
            npoints = xpoints.length;
        }
    }
    MyPoly poly = new MyPoly();

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w, h;

        g.clearRect(0, 0, getWidth(), getHeight());
        if(board == null) return;
        
        Graphics2D g2 = (Graphics2D) g;
        // g2.scale(edge,edge);

        // g2.setStroke(arg0)
        g2.setStroke(new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));

        g2.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < board.w; i++) {
            for (int j = 0; j < board.h; j++) {
                if (board.board[i][j] == board.WALL) {
                    g2.fillRect(i * ProtoBlock.edge, j * ProtoBlock.edge,
                            ProtoBlock.edge, ProtoBlock.edge);
                }
            }
        }

        for (KlotskiBoard.Block b : board.blocks) {
            g2.translate(b.x * ProtoBlock.edge, ProtoBlock.edge * b.y);
            poly.setArray(b.type.shape);
            if (b == board.donkey) {
                g2.setColor(Color.RED);
            } else {
                g2.setColor(Color.GREEN);
            }

            g2.fill(poly);
            g2.setColor(Color.BLACK);
            g2.draw(poly);
            g2.translate(-b.x * ProtoBlock.edge, -ProtoBlock.edge * b.y);

        }

    }
}
